<?php
namespace app\task\model;

use app\common\model\Order as OrderModel;
use app\common\model\Goods as GoodsModel;
use app\common\model\Device;
use think\facade\Cache;
use think\facade\Db;

/**
 * 订单模型
 */
class Order extends OrderModel
{
    /**
     * 待支付订单详情
     */
    public function payDetail($order_no)
    {
        return self::with(['goods','shop','table','address'])->where(['order_no' => $order_no, 'pay_status' => 10])->find();
    }

    /**
     * 更新付款状态
     */
    public function updatePayStatus($transaction_id)
    {
		
		if($this['pay_status']['value']==20){
			//避免重复回调
			return true;
		}
		
        // 开启事务
        Db::startTrans();
        try {
        	
			// 更新商品库存、销量
			$GoodsModel = new Goods;
			$GoodsModel->updateStockSales($this->goods);
			//天加交易记录
			$record = new Record;
			$record->save([
				'order_no' => $this['order_no'],
	            'money' => $this['pay_price'],
	            'user_id' => $this['user_id'],
	            'shop_id' => $this['shop_id'],
	            'applet_id' => $this['applet_id'],
	            'action' => 40,//消费
	            'type' => 30,//微信
	            'remark' => '订单支付'
			]);
			//更新用户信息
			$user = User::get($this->user_id);
			$user->pay = ['inc', $this->pay_price];//增加消费金额
			$user->score = ['inc', $this->pay_price];//增加积分
			$user->save();
			// 更新订单状态
			$this->save([
				'pay_status' => 20,
				'pay_time' => time(),
				'transaction_id' => $transaction_id,
			]);
			//发送新订单提醒，管理员,店长
			sand_new_order_msg($this);
			Device::print($this);//打印订单
			Device::push($this->shop_id,'pay',$this->pay_price);//收款提醒
			//商家是否自动接单
			if($this['shop']['is_order']['value'] == 1){
				$this->setShopStatus();
				//外卖自动推送订单
				if($this['order_mode']['value']==20 AND $this['shop']['is_delivery']['value'] == 1){
					$this->setDelivery($this['shop']['delivery']);
				}
			}
			Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
        }
        return false;
    }

	/**
     * 待退款订单详情
     */
    public function refundDetail($order_no)
    {
		return self::get(['order_no' => $order_no, 'order_status' => 40, 'refund_status' => 10], ['goods']);
    }
	
	/**
     * 更新退款款状态
     */
    public function updateRefundStatus($refund_id)
    {
		if(!empty($this->refund_id)){
			//避免重复回调
			return true;
		}
        // 开启事务
        Db::startTrans();
        try {
			//更新商品库存、销量
			//$GoodsModel = new Goods;
			//$GoodsModel->updateStockSales($this['goods']);
			//更新用户信息
			$user = User::get($this->user_id);
			$user->pay = ['dec', $this->refund_price];//扣减消费金额
			$user->score = ['dec', $this->refund_price];//扣减积分
			$user->save();
			//添加交易记录
			$record = new Record;
			$record->save([
				'order_no' => $this['order_no'],
	            'money' => $this['refund_price'],
	            'user_id' => $this['user_id'],
	            'shop_id' => $this['shop_id'],
	            'applet_id' => $this['applet_id'],
	            'action' => 60,//退款
	            'type' => 30,//微信
	            'remark' => '订单退款'
			]);
			// 更新订单状态
			$this->save([
				'refund_status' => 20,
				'refund_time' => time(),
				'refund_id' => $refund_id,
			]);
			//发送退款申请状态提醒订阅消息
			food_post_tpl('refund',$this->order_id);
			Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
        }
        return false;
    }
	
    
	
	/**
     * 更新第三方配送状态
     */
    public function updateDeliveryStatus($data,$mode)
    {
    	$dev['delivery_time'] = time();
		if($mode == 'dada'){
			//待接单＝1,待取货＝2,配送中＝3,已完成＝4,已取消＝5, 指派单=8,妥投异常之物品返回中=9, 妥投异常之物品返回完成=10, 骑士到店=100,创建达达运单失败=1000
			switch ((string)$data['order_status']) {
	            case '2': //已接单 - 骑手正赶往商家
					$dev = [
						'delivery_status' => 20,
						'linkman' => $data['dm_name'],
						'phone' => $data['dm_mobile']
					];
	                break;
	            case '100': //已到店 - 骑手已到店
					$dev = [
						'delivery_status' => 30
					];
	                break;
	            case '3': //已取件 - 骑手开始配送
					$dev = [
						'delivery_status' => 40
					];
	                break;
	            case '4';//到达目的地 - 骑手已送达
					$dev = [
						'delivery_status' => 50,
						'status' => 30
					];
	                break;
	            case '5': //订单被取消
					$dev = [
						'delivery_status' => 10,
						'shop_status' => 20
					];
					$this->save($dev);
	                break;
	            default:
	            	return true;
	        }
		}
		if($mode == 'sf'){
			switch ((string)$data['order_status']) {
	            case '10': //已接单 - 骑手正赶往商家
					$dev = [
						'delivery_status' => 20,
						'linkman' => $data['operator_name'],
						'phone' => $data['operator_phone']
					];
	                break;
	            case '12': //已到店 - 骑手已到店
					$dev = [
						'delivery_status' => 30
					];
	                break;
	            case '15': //已取件 - 骑手开始配送
					$dev = [
						'delivery_status' => 40
					];
	                break;
	            case '17';//到达目的地 - 骑手已送达
					$dev = [
						'delivery_status' => 50,
						'status' => 30
					];
	                break;
	            case '22': //订单被取消
					$dev = [
						'delivery_status' => 10,
						'shop_status' => 20
					];
					$this->save($dev);
	                break;
	            case '2': //订单被取消
					$dev = [
						'delivery_status' => 10,
						'shop_status' => 20
					];
					$this->save($dev);
	                break;
	            default:
	            	return true;
	        }
		}
		if($mode == 'uu'){
			//当前状态1下单成功 3跑男抢单 4已到达 5已取件 6到达目的地 10收件人已收货 -1订单取消
			switch ((string)$data['state']) {
	            case '3': //已接单 - 骑手正赶往商家
					$dev = [
						'delivery_status' => 20,
						'linkman' => $data['driver_name'],
						'phone' => $data['driver_mobile']
					];
	                break;
	            case '4': //已到店 - 骑手已到店
					$dev = [
						'delivery_status' => 30
					];
	                break;
	            case '5': //已取件 - 骑手开始配送
					$dev = [
						'delivery_status' => 40
					];
	                break;
	            case '6';//到达目的地 - 骑手已送达
					$dev = [
						'delivery_status' => 50,
						'status' => 30
					];
	                break;
	            case '-1': //订单被取消
					$dev = [
						'delivery_status' => 10,
						'shop_status' => 20
					];
					$this->save($dev);
	                break;
	            default:
	            	return true;
	        }
		}
		if($mode == 'make'){
			//loading = 待付款', cancel='订单已取消', payed='待接单',wait_to_shop='待到店', accepted='待取件', geted='待收件',gotoed= '待评价', completed='订单已完成');
			switch ($data['status']) {
	            case 'wait_to_shop': //已接单 - 骑手正赶往商家
					$dev = [
						'delivery_status' => 20,
						'linkman' => $data['rider_name'],
						'phone' => $data['rider_mobile']
					];
	                break;
	            case 'accepted': //已到店 - 骑手已到店
					$dev = [
						'delivery_status' => 30
					];
	                break;
	            case 'geted': //已取件 - 骑手开始配送
					$dev = [
						'delivery_status' => 40
					];
	                break;
	            case 'completed';//到达目的地 - 骑手已送达
					$dev = [
						'delivery_status' => 50,
						'status' => 30
					];
	                break;
	            case 'cancel': //订单被取消
					$dev = [
						'delivery_status' => 10,
						'shop_status' => 20
					];
					$this->save($dev);
	                break;
	            default:
	            	return true;
	        }
		}
		$delivery = (new OrderDelivery)->where('order_id',$this->order_id)->find();
		$delivery->save($dev);
		return true;
	}

}
